<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="4">
        <el-input v-model="formData.city" disabled placeholder="城市"></el-input>
      </el-col>
      <el-col :span="4">
        <el-input v-model="formData.district" disabled placeholder="区县"></el-input>
      </el-col>
      <el-col :span="6">
        <el-select
          v-model="formData.streetOfPhotoLocation"
          clearable
          filterable
          :disabled="disabled"
          placeholder="请选择街道"
          @change="handleChange">
          <el-option
            v-for="(item, index) in street_of_area"
            :key="item.value"
            :label="item.label"
            :value="item.value"></el-option>
        </el-select>
      </el-col>
      <el-col :span="10">
        <el-input
          v-model="formData.photoLocation"
          :disabled="disabled"
          placeholder="详细地址"
          @change="handleChange"></el-input>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, getCurrentInstance } from 'vue'
import settings from '@/settings.js'

interface LocationData {
  city?: string
  district?: string
  streetOfPhotoLocation?: string
  photoLocation?: string
}

const { proxy } = getCurrentInstance()
const { street_of_area } = proxy.useDict('street_of_area')

const props = defineProps({
  modelValue: {
    type: [String, Object] as any,
    default: () => ({}),
  },
  disabled: {
    type: Boolean,
    default: false,
  },
})

const emit = defineEmits(['update:modelValue'])

const formData = ref<LocationData>({
  city: settings.cityName,
  district: settings.areaName,
  streetOfPhotoLocation: '',
  photoLocation: '',
})

// 初始化时设置数据
onMounted(() => {
  if (props.modelValue && typeof props.modelValue === 'object') {
    formData.value = {
      ...formData.value,
      streetOfPhotoLocation: props.modelValue.streetOfPhotoLocation || '',
      photoLocation: props.modelValue.photoLocation || '',
    }
  }
})

// 监听外部传入值的变化（仅在值真正改变时更新）
watch(
  () => props.modelValue,
  (newVal, oldVal) => {
    if (newVal && typeof newVal === 'object' && JSON.stringify(newVal) !== JSON.stringify(oldVal)) {
      formData.value = {
        ...formData.value,
        streetOfPhotoLocation: newVal.streetOfPhotoLocation || '',
        photoLocation: newVal.photoLocation || '',
      }
    }
  }
)

const handleChange = () => {
  // 只在用户选择街道时触发更新
  emit('update:modelValue', { ...formData.value })
}
</script>

<style scoped></style>
